// 运行时配置
import React from 'react';
import { menuData } from './constants/menu';
import * as Icons from '@ant-design/icons';

// 动态获取图标组件
const getIcon = (name: string) => {
  if (!name) return null;
  const IconComponent = (Icons as any)[name];
  return IconComponent ? <IconComponent /> : null;
};

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<{ 
  name: string;
  access?: Record<string, boolean>;
}> {
  // 这里可以从服务器获取用户信息和权限
  return { 
    name: '管理员',
    access: {
      canAccessUser: true,
      canAccessRole: true,
      canAccessPermission: true,
      canAccessMenu: true,
      canAccessSystem: true,
    },
  };
}

export const layout = ({ initialState }: { initialState: any }) => {
  return {
    logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    menu: {
      locale: false,
      defaultOpenAll: true,
      request: async () => {
        // 直接使用路由配置作为菜单数据
        // 处理图标并返回菜单数据
        const processMenuData = (items: any[]) => {
          return items.map(item => {
            const result = { ...item };
            
            // 处理图标
            if (item.icon) {
              result.icon = getIcon(item.icon);
            }
            
            // 处理子菜单
            if (item.routes) {
              result.children = processMenuData(item.routes.filter((route: any) => !route.hideInMenu));
              // 如果没有可见的子菜单，则不显示此菜单项
              if (result.children.length === 0) {
                delete result.children;
              }
            }
            
            return result;
          });
        };
        
        return processMenuData(menuData);
      },
    },
  };
};
